import { ref, onMounted, watch } from 'vue'

const THEME_KEY = 'theme-mode'
const DARK_CLASS = 'dark-mode'

export function useTheme() {
  const isDarkMode = ref(false)

  // 切换主题
  const toggleTheme = () => {
    isDarkMode.value = !isDarkMode.value
    updateTheme()
  }

  // 更新主题
  const updateTheme = () => {
    // 更新body类名
    if (isDarkMode.value) {
      document.body.classList.add(DARK_CLASS)
    } else {
      document.body.classList.remove(DARK_CLASS)
    }

    // 保存到本地存储
    localStorage.setItem(THEME_KEY, isDarkMode.value ? 'dark' : 'light')
  }

  // 初始化主题
  const initTheme = () => {
    // 优先使用本地存储的主题
    const savedTheme = localStorage.getItem(THEME_KEY)
    if (savedTheme) {
      isDarkMode.value = savedTheme === 'dark'
    } else {
      // 否则使用系统主题
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
      isDarkMode.value = prefersDark
    }
    updateTheme()
  }

  // 监听系统主题变化
  const handleSystemThemeChange = (e) => {
    // 只有在没有本地存储的主题时才跟随系统主题
    if (!localStorage.getItem(THEME_KEY)) {
      isDarkMode.value = e.matches
      updateTheme()
    }
  }

  onMounted(() => {
    initTheme()

    // 监听系统主题变化
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    mediaQuery.addListener(handleSystemThemeChange)

    // 组件卸载时移除监听
    return () => {
      mediaQuery.removeListener(handleSystemThemeChange)
    }
  })

  // 监听主题变化，更新CSS变量
  watch(isDarkMode, (isDark) => {
    const root = document.documentElement
    if (isDark) {
      root.style.setProperty('--bg-color', '#1f1f1f')
      root.style.setProperty('--component-bg', '#2d2d2d')
      root.style.setProperty('--text-color', '#e6e6e6')
      root.style.setProperty('--text-color-secondary', '#a6a6a6')
      root.style.setProperty('--border-color', '#434343')
      root.style.setProperty('--primary-color', '#1890ff')
      root.style.setProperty('--highlight-bg', '#111b26')
    } else {
      root.style.setProperty('--bg-color', '#f5f5f5')
      root.style.setProperty('--component-bg', '#ffffff')
      root.style.setProperty('--text-color', '#262626')
      root.style.setProperty('--text-color-secondary', '#595959')
      root.style.setProperty('--border-color', '#d9d9d9')
      root.style.setProperty('--primary-color', '#1890ff')
      root.style.setProperty('--highlight-bg', '#e6f7ff')
    }
  }, { immediate: true })

  return {
    isDarkMode,
    toggleTheme
  }
} 